<template>
    <div class="outer-order-page">
      <el-button type="primary" @click="saveAll">保存</el-button>
  
      <!-- 基本信息部分 -->
      <br/><br/>
      <el-card title="基本信息">
        <el-form 
          :model="form" 
          label-width="120px" 
          ref="formRef" 
          :rules="rules"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="单据主题" prop="documentSubject">
                <el-input v-model="form.documentSubject" required></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据编号" prop="documentNumber">
                <el-input placeholder="保存后自动生成" disabled v-model="form.documentNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联生产订单" prop="associateProductionOrder">
                <el-input
                  placeholder="请输入"
                  v-model="form.associateProductionOrder"
                  required
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="8">
              <el-form-item label="委外加工商" prop="processors">
                <el-input
                  v-model="form.processors"
                  :readonly="form.processorsInfoFilled"
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openProcessorsDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="对方代表">
                <el-input
                  v-model="form.client"
                  :readonly="form.clientInfoFilled"
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openClientDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="我方代表" prop="ourRepresentatives">
                <el-input
                  v-model="form.ourRepresentatives"
                  :readonly="form.ourRepresentativesInfoFilled"
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openOurRepresentativesDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="8">
              <el-form-item label="付款计划">
                <el-select v-model="form.paymentPlan" placeholder="请选择" required>
                  <el-option label="自动生成" value="自动生成"></el-option>
                  <el-option label="手动生成" value="手动生成"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收票计划">
                <el-select v-model="form.ticketCollectionPlan" placeholder="请选择" required>
                  <el-option label="自动生成" value="自动生成"></el-option>
                  <el-option label="手动生成" value="手动生成"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否自动收货送检" label-width="140px">
                <el-radio-group v-model="form.automaticallyReceivedInspection" required>
                  <el-radio :label="false">否</el-radio>
                  <el-radio :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="8">
              <el-form-item label="是否带料">
                <el-radio-group v-model="form.whetherMaterials" required>
                  <el-radio :label="false">否</el-radio>
                  <el-radio :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="委外日期" prop="dateOutsourcing">
                <el-date-picker v-model="form.dateOutsourcing" type="date" placeholder="选择日期" required></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="制单日期">
                <el-date-picker v-model="form.preparationDocumentsDate" type="date" placeholder="选择日期" disabled></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="8">
              <el-form-item label="制单人员">
                <el-input v-model="form.preparationDocumentsPerson" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
            <el-form-item label="*关联项目" prop="associatedProjects">
              <el-input
                placeholder="请选择项目"
                v-model="form.associatedProjects"
                required
              >
                <template #suffix>
                  <el-button size="mini" @click="openAssociatedItemDialog">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
            <el-col :span="16">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
  
      <!-- 委外产品明细部分 -->
      <el-card title="委外产品明细">
        <div class="table-operations">
          <el-button type="primary" size="small" @click="addRow">增行</el-button>
          <el-button size="small" @click="deleteRow">删行</el-button>
        </div>
  
        <el-table 
          :data="productList" 
          border 
          style="width: 100%" 
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" v-model="multipleSelection"></el-table-column>
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column label="产品名称" width="180px">
            <template #default="{ row }">
              <el-input
                v-model="row.productName"
                :readonly="row.productInfoFilled"
              >
                <template #suffix>
                  <el-button size="mini" @click="openProductNameDialog(row)">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="产品编号" width="180px">
            <template #default="{ row }">
              <el-input v-model="row.productNumber" :disabled="row.productInfoFilled"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="180px">
            <template #default="{ row }">
              <el-input v-model="row.specifications" :disabled="row.productInfoFilled"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位" width="180px">
            <template #default="{ row }">
              <el-input v-model="row.unit" :disabled="row.productInfoFilled"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="订单数量" prop="orderQuantity" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.orderQuantity"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="已委外数量" prop="outsourcingSum" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.outsourcingSum"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="*本次委外数量" prop="outsourcingNumber" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.outsourcingNumber" required></el-input>
            </template>
          </el-table-column>
          <el-table-column label="*委外单价" prop="outsourcingPrice" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.outsourcingPrice" required></el-input>
            </template>
          </el-table-column>
          <el-table-column label="*票据类型" prop="ticketType" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.ticketType" required></el-input>
            </template>
          </el-table-column>
          <el-table-column label="*税率(%)" prop="rate">
            <template #default="scope">
              <el-input v-model="scope.row.rate" required></el-input>
            </template>
          </el-table-column>
          <el-table-column label="委外含税单价" prop="outsourcingIncludesPrice" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.outsourcingIncludesPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="price">
            <template #default="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="税额" prop="tax">
            <template #default="scope">
              <el-input v-model="scope.row.tax"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="总金额" prop="totalAmount">
            <template #default="scope">
              <el-input v-model="scope.row.totalAmount"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="交货日期" prop="delivery" width="100">
            <template #default="scope">
              <el-date-picker v-model="scope.row.delivery" type="date" placeholder="选择日期"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <!-- 产品名称选择对话框 -->
      <el-dialog
        v-model="productNameDialogVisible"
        width="500px"
        title="产品名称选择"
        append-to-body
      >
        <el-table
          :data="productNames"
          highlight-current-row
          border
          size="small"
          @current-change="handleProductNameChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="productsNumber" label="产品编号" />
          <el-table-column property="productsName" label="产品名称" />
          <el-table-column property="productsNum" label="规格型号" />
          <el-table-column property="productsUnit" label="单位" />
        </el-table>
        <template #footer>
          <el-button @click="productNameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickProductName">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 委外加工商选择对话框 -->
      <el-dialog
        v-model="processorsDialogVisible"
        width="500px"
        title="委外加工商选择"
        append-to-body
      >
        <el-table
          :data="processorsList"
          highlight-current-row
          border
          size="small"
          @current-change="handleProcessorsChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="vendorId" label="加工商ID" />
          <el-table-column property="vendorName" label="加工商名称" />
          <el-table-column property="contact" label="联系人" />
          <el-table-column property="phone" label="联系电话" />
        </el-table>
        <template #footer>
          <el-button @click="processorsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickProcessors">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 对方代表选择对话框 -->
      <el-dialog
        v-model="clientDialogVisible"
        width="500px"
        title="对方代表选择"
        append-to-body
      >
        <el-table
          :data="clientList"
          highlight-current-row
          border
          size="small"
          @current-change="handleClientChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="clientId" label="客户ID" />
          <el-table-column property="clientName" label="客户名称" />
          <el-table-column property="contactName" label="代表姓名" />
          <el-table-column property="email" label="邮箱" />
        </el-table>
        <template #footer>
          <el-button @click="clientDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickClient">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 我方代表选择对话框 -->
      <el-dialog
        v-model="ourRepresentativesDialogVisible"
        width="500px"
        title="我方代表选择"
        append-to-body
      >
        <el-table
          :data="ourRepresentativesList"
          highlight-current-row
          border
          size="small"
          @current-change="handleOurRepresentativesChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="userName" label="代表姓名" />
          <el-table-column property="depmentName" label="部门" />
          <el-table-column property="roleName" label="职位" />
        </el-table>
        <template #footer>
          <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
        </template>
      </el-dialog>

      <!-- 关联项目选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible"
      width="500px"
      title="关联项目选择"
      append-to-body
    >
      <el-table
        :data="associatedItems"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="projectNum" label="项目编号" />
        <el-table-column prop="projectTime" label="项目日期" />
        <el-table-column prop="projectPeople" label="项目负责人" />
        <el-table-column prop="projectTypeId" label="项目分类" />
      </el-table>
      <template #footer>
        <el-button @click="associatedItemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="pickAssociatedItem">确定</el-button>
      </template>
    </el-dialog>

    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import axios from 'axios';
  import { useCounterStore } from '@/stores/counter'
  import { write, read } from '@/axios/axiosHelper'

  const store = useCounterStore();
  
  // 表单验证规则
  const rules = reactive({
    documentSubject: [{ required: true, message: '请输入单据主题', trigger: 'blur' }],
    associateProductionOrder: [{ required: true, message: '请输入关联生产订单', trigger: 'blur' }],
    processors: [{ required: true, message: '请选择委外加工商', trigger: 'blur' }],
    client: [{ required: true, message: '请选择对方代表', trigger: 'blur' }],
    ourRepresentatives: [{ required: true, message: '请选择我方代表', trigger: 'blur' }],
    paymentPlan: [{ required: true, message: '请选择付款计划', trigger: 'change' }],
    ticketCollectionPlan: [{ required: true, message: '请选择收票计划', trigger: 'change' }],
    automaticallyReceivedInspection: [{ required: true, message: '请选择是否自动收货送检', trigger: 'change' }],
    whetherMaterials: [{ required: true, message: '请选择是否带料', trigger: 'change' }],
    dateOutsourcing: [{ required: true, message: '请选择委外日期', trigger: 'change' }],
    associatedProjects: [{ required: true, message: '请输入关联项目', trigger: 'blur' }]
  });
  
  // 基本信息表单数据
  const form = ref({
    documentSubject: "",
    documentNumber: "",
    associateProductionOrder: "",
    processors: "",
    processorsInfoFilled: false,
    client: "",
    clientInfoFilled: false,
    ourRepresentatives: "",
    ourRepresentativesInfoFilled: false,
    paymentPlan: "",
    ticketCollectionPlan: "",
    automaticallyReceivedInspection: false,
    whetherMaterials: false,
    dateOutsourcing: null,
    preparationDocumentsDate: new Date(),
    preparationDocumentsPerson:store.counterStore.userName,
    associatedProjects: "",
    remark: ""
  });
  
  // 委外产品明细数据
  const productList = ref([{
    productName: "",
    productNumber: "",
    specifications: "",
    unit: "",
    orderQuantity: 0,
    outsourcingSum: 0,
    outsourcingNumber: 0,
    outsourcingPrice: 0,
    ticketType: "",
    rate: 0,
    outsourcingIncludesPrice: 0,
    price: 0,
    tax: 0,
    totalAmount: 0,
    delivery: null,
    remark: "",
    productInfoFilled: false
  }]);
  
  // 表单ref
  const formRef = ref(null);
  
  // 选中行管理
  const multipleSelection = ref([]);
  const handleSelectionChange = (val) => {
    multipleSelection.value = val;
  };
  
  // 增行方法
  const addRow = () => {
    productList.value.push({
      productName: '',
      productNumber: '',
      specifications: '',
      unit: '',
      orderQuantity: 0,
      outsourcingSum: 0,
      outsourcingNumber: 0,
      outsourcingPrice: 0,
      ticketType: '',
      rate: 0,
      outsourcingIncludesPrice: 0,
      price: 0,
      tax: 0,
      totalAmount: 0,
      delivery: null,
      remark: '',
      productInfoFilled: false
    });
  };
  
  // 删行方法
  const deleteRow = () => {
    if (multipleSelection.value.length > 0) {
      productList.value = productList.value.filter(row => 
        !multipleSelection.value.includes(row)
      );
      ElMessage.success('删除成功');
    } else {
      ElMessage.warning('请先选择要删除的行');
    }
  };
  
  // 保存主表单和明细
  const saveAll = async () => {
    if (!formRef.value) return;
  
    const isValid = await formRef.value.validate();
    if (!isValid) return;
  
    try {
      // 保存主表单
      const mainResponse = await write.post(
        'w-write/api/Outsourcing/AddOutsourcing',
        form.value
      );
  
      if (mainResponse.data.code === 100) {
        ElMessage.success('主表单保存成功');
        const outsourcingId = mainResponse.data.data.outsourcingId;
  
        // 保存明细数据
        const detailPromises = productList.value.map(async (row) => {
          const detailData = {
            ...row,
            outsourcingId: outsourcingId
          };
          return write.post(
            'w-write/api/Outsourcing/AddOutsourcingDetail',
            detailData
          );
        });
  
        await Promise.all(detailPromises);
        ElMessage.success('所有明细保存成功');
      } else {
        ElMessage.error(`主表单保存失败：${mainResponse.data.message}`);
      }
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
    }
  };
  
  // 对话框相关响应式数据
  const productNameDialogVisible = ref(false);
  const productNames = ref([]);
  const currentProductNameRow = ref(null);
  const currentProductName = ref(null);
  
  const processorsDialogVisible = ref(false);
  const processorsList = ref([]);
  const currentProcessors = ref(null);
  
  const clientDialogVisible = ref(false);
  const clientList = ref([]);
  const currentClient = ref(null);
  
  const ourRepresentativesDialogVisible = ref(false);
  const ourRepresentativesList = ref([]);
  const currentOurRepresentative = ref(null);
  
  // 生命周期钩子
  onMounted(() => {
    fetchBaseData();
    fetchProductNames();
  });
  
  // 获取基础数据
  const fetchBaseData = () => {
    // 委外加工商
    read.get("w2-read/api/Vendor/QueryVendor")
      .then(res => processorsList.value = res.data.data || [])
      .catch(error => {
        ElMessage.error('加载委外加工商失败');
        console.error(error);
      });
  
    // 对方代表（客户代表）
    read.get("w2-read/api/Client/GetClient")
      .then(res => clientList.value = res.data.data || [])
      .catch(error => {
        ElMessage.error('加载对方代表失败');
        console.error(error);
      });
  
    // 我方代表（员工代表）
    read.get("read/api/Depment/GetDepUserRole")
      .then(res => ourRepresentativesList.value = res.data.data || [])
      .catch(error => {
        ElMessage.error('加载我方代表失败');
        console.error(error);
      });
  };

 // 关联项目对话框数据
const associatedItemDialogVisible = ref(false);
const associatedItems = ref([]);
const currentAssociatedItem = ref(null);

// 生命周期：加载关联项目数据
onMounted(() => {
  fetchAssociatedProjects();
});

// 获取关联项目列表
const fetchAssociatedProjects = () => {
  read.get('w-read/api/Project/ShowProject')
    .then(res => {
      associatedItems.value = res.data.data || [];
    })
    .catch(error => {
      ElMessage.error('加载关联项目失败，请检查网络');
      console.error(error);
    });
};

// 打开关联项目对话框
const openAssociatedItemDialog = () => {
  if (associatedItems.value.length === 0) {
    ElMessage.warning('项目数据加载中，请稍后');
    return;
  }
  associatedItemDialogVisible.value = true;
};

// 处理项目选中
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};

// 选择项目并填充数据
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    form.value.associatedProjects = currentAssociatedItem.value.projectName;
    associatedItemDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个项目');
  }
};
  
  // 获取产品信息
  const fetchProductNames = () => {
    read.get("w2-read/api/Products/GetProducts")
      .then(res => productNames.value = res.data.data || [])
      .catch(error => {
        ElMessage.error('获取产品信息失败:', error);
        console.error(error);
      });
  };
  
  // 打开产品名称选择对话框
  const openProductNameDialog = (row) => {
    if (productNames.value.length === 0) {
      ElMessage.warning('产品信息正在加载，请稍后重试');
      return;
    }
    currentProductNameRow.value = row;
    productNameDialogVisible.value = true;
  };
  
  // 处理产品行选中
  const handleProductNameChange = (val) => {
    currentProductName.value = val;
  };
  
  // 选择产品并填充数据
  const pickProductName = () => {
    if (currentProductName.value && currentProductNameRow.value) {
      const { productsName, productsNumber, productsNum, productsUnit } = currentProductName.value;
      currentProductNameRow.value.productName = productsName;
      currentProductNameRow.value.productNumber = productsNumber;
      currentProductNameRow.value.specifications = productsNum;
      currentProductNameRow.value.unit = productsUnit;
      currentProductNameRow.value.productInfoFilled = true;
      productNameDialogVisible.value = false;
    } else {
      ElMessage.warning('请先选择一个产品');
    }
  };
  
  // 打开委外加工商对话框
  const openProcessorsDialog = () => {
    if (processorsList.value.length === 0) {
      ElMessage.warning('加工商数据加载中，请稍后重试');
      return;
    }
    processorsDialogVisible.value = true;
  };
  
  // 处理委外加工商行选中
  const handleProcessorsChange = (val) => {
    currentProcessors.value = val;
  };
  
  // 选择委外加工商并填充数据
  const pickProcessors = () => {
    if (currentProcessors.value) {
      form.value.processors = currentProcessors.value.vendorName;
      form.value.processorsInfoFilled = true;
      processorsDialogVisible.value = false;
    } else {
      ElMessage.warning('请选择一个委外加工商');
    }
  };
  
  // 打开对方代表对话框
  const openClientDialog = () => {
    if (clientList.value.length === 0) {
      ElMessage.warning('客户代表数据加载中，请稍后重试');
      return;
    }
    clientDialogVisible.value = true;
  };
  
  // 处理对方代表行选中
  const handleClientChange = (val) => {
    currentClient.value = val;
  };
  
  // 选择对方代表并填充数据
  const pickClient = () => {
    if (currentClient.value) {
      form.value.client = currentClient.value.clientName;
      form.value.clientInfoFilled = true;
      clientDialogVisible.value = false;
    } else {
      ElMessage.warning('请选择一个对方代表');
    }
  };
  
  // 打开我方代表对话框
  const openOurRepresentativesDialog = () => {
    if (ourRepresentativesList.value.length === 0) {
      ElMessage.warning('我方代表数据加载中，请稍后重试');
      return;
    }
    ourRepresentativesDialogVisible.value = true;
  };
  
  // 处理我方代表行选中
  const handleOurRepresentativesChange = (val) => {
    currentOurRepresentative.value = val;
  };
  
  // 选择我方代表并填充数据
  const pickOurRepresentatives = () => {
    if (currentOurRepresentative.value) {
      form.value.ourRepresentatives = currentOurRepresentative.value.userName;
      form.value.ourRepresentativesInfoFilled = true;
      ourRepresentativesDialogVisible.value = false;
    } else {
      ElMessage.warning('请选择一个我方代表');
    }
  };
  </script>
  
  <style scoped>
  .outer-order-page {
    padding: 20px;
  }
  
  .table-operations {
    margin: 10px 0 20px;
    display: flex;
    gap: 8px;
  }
  
  .el-form-item {
    margin-bottom: 12px;
  }
  
  .el-table {
    margin-top: 15px;
  }
  
  .el-input__append {
    padding-right: 8px;
  }
  </style>
      